package dbclient

import (
	"UbiOsCommCore/utils"
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"os"
)

type DBConfig struct {
	Password   string
	Username   string
	Host       string
	Port       int
	ServerName string
	DbName     string
	DbType     string
}

type DBClient struct {
	configPath string
	config     DBConfig
	db         *sqlx.DB
	operation  SqlOperation
}

type SqlOperation interface {
	Find(tableName string, params []interface{}, page map[string]interface{}) string
}

type MySqlImpl struct{}

func (dbClient *DBClient) DBInit() {
	dbClient.readConfig()
	if dbClient.config.DbType == "mysql" {
		dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", dbClient.config.Username, dbClient.config.Password, dbClient.config.Host, dbClient.config.Port, dbClient.config.DbName)
		db, err := sqlx.Connect("mysql", dataSourceName)
		if err != nil {
			utils.Log.Error(err)
		}
		dbClient.db = db
		dbClient.operation = &MySqlImpl{}
	}
}

func (dbClient *DBClient) readConfig() {
	j, err := os.ReadFile(dbClient.configPath)
	if err != nil {
		utils.Log.Printf("读取文件错误: %s\n", err)
		return
	}

	var config DBConfig
	err = json.Unmarshal(j, &config)
	if err != nil {
		utils.Log.Printf("解析JSON错误: %s\n", err)
		return
	}
	dbClient.config = config
}

func (dbClient *DBClient) Close() {
	err := dbClient.db.Close()
	if err != nil {
		panic("some error occur while sql closed ")
	}
}

func (mysqlImpl *MySqlImpl) Find(tableName string, params []interface{}, page map[string]interface{}) string {
	sqlStr := fmt.Sprintf("select* from %s", tableName)
	if len(params) == 0 {
		//没有参数就取全部
	}
	sqlStr += " where "
	for _, t := range params {
		tt := t.(map[string]interface{})
		if _, ok := tt["join"]; ok {
		} else {
			tt["join"] = "and"
		}
		switch tt["value"].(type) {
		case float64:
			//tt
		}
		tmpStr := fmt.Sprintf("%s %s='%s'", tt["join"], tt["key"], tt["value"])
		sqlStr += tmpStr
	}
	println(sqlStr)
	//fmt.Println(tableName)
	//fmt.Println(params)
	//fmt.Println(page)
	return "mysql"
}
